$cangjie_code = {}

def build_cangjie(filepath)
  File.readlines(filepath).each do |line|
    next if line =~ /^[a-z|#|\s|\-|.]/

    character, code = line.chomp.split("\t")

    if $cangjie_code.has_key?(character)
      next if $cangjie_code[character].include?(code)

      $cangjie_code[character] << code

    else
      $cangjie_code[character] = [code]
    end
  end
end

def build_characters(filepath)
  basename = File.basename(filepath)
  filename = basename.split('.').first
  f = File.new("cjs/#{basename}", 'w')
  f.write("---\n")
  f.write("name: #{filename}\n")
  f.write(%(version: "#{Time.now.to_i}"\n))
  f.write("sort: by_weight\n")
  f.write("...\n\n")
  l = {}
  File.readlines(filepath).each do |line|
    next if line =~ /^[a-z|#|\s|\-|.]/

    character, _, weight = line.chomp.split("\t")
    next if l.has_key?(character)

    l[character] = weight
  end

  l.each do |k, v|
    $cangjie_code[k].each do |cangjie|
      f.write "#{k}\t#{cangjie}\t#{v}\n"
    end
  end

  f.close
end

def get_quick(character)
    quick = []
    # 词的单字可能有容错码字可能有容错码
    $cangjie_code[character].each do |cangjie|
      next if cangjie =~ /^[z|x]/

      # 每个字的全部速成码构成一个数组
      quick << if cangjie.length > 1

                  # 多码字取首尾
                  cangjie[0] + cangjie[-1]

                else
                  # 单码取本身
                  cangjie
                end
    end
    return quick.uniq
end

def build_words(filepath)
  basename = File.basename(filepath)
  filename = basename.split('.').first
  f = File.new("cjs/#{basename}", 'w')
  f.write("---\n")
  f.write("name: #{filename}\n")
  f.write(%(version: "#{Time.now.to_i}"\n))
  f.write("sort: by_weight\n")
  f.write("...\n\n")
  File.readlines(filepath).each do |line|
    next if line =~ /^[a-z|#|\s|\-|.]/

    words, _, weight = line.chomp.split("\t")

    quicks = []
    words.split('').each do |character|
      # 不同的仓颉码取速成后，可能是一样的
      quicks << get_quick(character)
    end
    # 每个字的多个码的笛卡尔积
    products = quicks.shift.product(*quicks)
    products.each do |p|
      f.write("#{words}\t#{p.join(' ')}\t#{weight}\n")
    end
  end
  f.close
end

build_cangjie('./cangjie_dict/big.dict.yaml')

build_characters('./rime-frost/cn_dicts/8105.dict.yaml')
build_characters('./rime-frost/cn_dicts/41448.dict.yaml')

build_words('./rime-frost/cn_dicts/base.dict.yaml')
build_words('./rime-frost/cn_dicts/ext.dict.yaml')
build_words('./rime-frost/cn_dicts/tencent.dict.yaml')

# $cangjie_code.each do | k, v |
#   v.each do |i|
#     puts "#{k}\t#{i}"
#   end
# end
#
# puts get_quick("底")
